import enquireJs from 'enquire.js';
import { JSEncrypt } from 'jsencrypt';
import { message } from 'ant-design-vue';
export function isDef(v) {
  return v !== undefined && v !== null;
}

/**
 * Remove an item from an array.
 */
export function remove(arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item);
    if (index > -1) {
      return arr.splice(index, 1);
    }
  }
}

export const downloadUrl = (res, fileName, type) => {
  const blob = new Blob([res], { type });
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, fileName);
  } else {
    const elink = document.createElement('a');
    elink.download = fileName;
    elink.style.display = 'none';
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href);
    document.body.removeChild(elink);
  }
  message.success('成功导出');
};

export function isRegExp(v) {
  return _toString.call(v) === '[object RegExp]';
}

export function enquireScreen(call) {
  const handler = {
    match: function() {
      call && call(true);
    },
    unmatch: function() {
      call && call(false);
    }
  };
  enquireJs.register('only screen and (max-width: 767.99px)', handler);
}

const _toString = Object.prototype.toString;

// 防抖
export const debounce = (func, wait) => {
  let timer;
  return function() {
    const args = arguments;

    if (timer) clearTimeout(timer);

    timer = setTimeout(() => {
      func.apply(this, args);
    }, wait);
  };
};
// 延迟
export const delay = (wait) => {
  return new Promise(resolve => setTimeout(resolve, wait));
};

// 参数说明：
// number：要格式化的数字
// decimals：保留几位小数
// dec_point：小数点符号
// thousands_sep：千分位符号

export const number_format = (number, decimals, dec_point, thousands_sep) => {
  number = (number + '').replace(/[^0-9+-Ee.]/g, '');
  var n = !isFinite(+number) ? 0 : +number;
  var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals);
  var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
  var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
  var s = '';
  var toFixedFix = function(n, prec) {
    var k = Math.pow(10, prec);
    return '' + Math.ceil(n * k) / k;
  };

  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
  var re = /(-?\d+)(\d{3})/;
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, '$1' + sep + '$2');
  }

  if ((s[1] || '').length < prec) {
    s[1] = s[1] || '';
    s[1] += new Array(prec - s[1].length + 1).join('0');
  }
  return s.join(dec);
};

// rsa加密
export const encryptedData = (pk, data) => {
  const encryptor = new JSEncrypt();
  encryptor.setPublicKey(pk);
  return encryptor.encrypt(data);
};

export const getQueryString = (name) => {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
};
